// 单点登录核心类
import { getToken } from '/@/utils/auth';
import { getUrlParam } from '/@/utils';
import { useGlobSetting } from '/@/hooks/setting';
import { validateCasLogin } from '/@/api/sys/user';
import { useUserStore } from '/@/store/modules/user';
import { ref } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import qs from 'qs';

const globSetting = useGlobSetting();
const openSso = globSetting.openSso;
export function useSso() {
  //update-begin---author:wangshuai---date:2024-01-03---for:【QQYUN-7805】SSO登录强制用http #957---
  let locationUrl = document.location.protocol + '//' + window.location.host + '/';
  //update-end---author:wangshuai---date:2024-01-03---for:【QQYUN-7805】SSO登录强制用http #957---

  /**
   * 单点登录
   */
  async function ssoLogin() {
    if (openSso == 'true') {
      let token = getToken();
      let ticket = getUrlParam('ticket');
      if (!token) {
        if (ticket) {
          await validateCasLogin({
            ticket: ticket,
            service: locationUrl,
          }).then((res) => {
            const userStore = useUserStore();
            userStore.setToken(res.token);
            return userStore.afterLoginAction(true, {});
          });
        } else {
          window.location.href = globSetting.casBaseUrl + '/login?service=' + encodeURIComponent(locationUrl);
        }
      }
    }
  }

  /**
   * 退出登录
   */
  async function ssoLoginOut() {
    const loginOutUri = localStorage.getItem('loginOutUri')
    if (loginOutUri) {
      localStorage.removeItem('loginOutUri');
      window.open(loginOutUri + '?redirectToLogin=true&redirectToUrl=' + window.location.origin, '_self');;
    }
    // window.location.href = globSetting.casBaseUrl + '/logout?service=' + encodeURIComponent(locationUrl);
  }
  return { ssoLogin, ssoLoginOut };
}

interface CONFIG {
  authorizationUri: string;
  loginOutUri: string;
  clientId: string;
  responseType: string;
  clientSecret: string;
  state: string;
  tanantId: string;
  [key: string]: any;
}

// 竹云单点登录
export function useSsozy() {
  let authConfig = ref<CONFIG | null>(null);

  // 获取系统竹云配置信息，目前对接竹云林芝服务，配置接口有调整
  const getConfig = async () => {
    const res = await defHttp.request({
      url: '/sys/oauth/info',
      method: 'get',
    });
    authConfig.value = res;
    return res;
  };

  // 竹云认证地址
  const getAuthPath = async (data?: Record<string, any>) => {
    if (!authConfig.value) {
      await getConfig();
    }
    const { clientId, responseType, state, redirectUri, authorizationUri } = authConfig.value!;
    const params = {
      client_id: clientId,
      redirect_uri: encodeURI(redirectUri),
      response_type: responseType,
      state,
      ...(data || {}),
    };

    return `${authorizationUri}?${qs.stringify(params)}`;
  };

  // 竹云回调返回code换取业务token
  const ssoLogin = async (data?: Record<string, any>) => {
    const code = getUrlParam('code');
    const state = getUrlParam('state');
    if (!code || !state) {
      return;
    }
    const res = await defHttp.request({
      url: '/sys/oauth/Login',
      method: 'get',
      params: { code, state, ...(data || {}) },
    });
    const userStore = useUserStore();
    userStore.setToken(res?.token);
    res?.loginOutUri && localStorage.setItem('loginOutUri', res?.loginOutUri);
    return userStore.afterLoginAction(true, { usaLogin: true });
  };

  // 竹云单点统一退出
  const ssoLoginOut = async () => {
    if (!authConfig.value) {
      await getConfig();
    }
    if (authConfig.value?.loginOutUri) {
      window.location.href = authConfig.value.loginOutUri + '?redirectToLogin=true&redirectToUrl=' + window.location.origin;
    }
  };

  return {
    authConfig,
    getConfig,
    getAuthPath,
    ssoLogin,
    ssoLoginOut,
  };
}
